﻿<?php if (!file_exists(__DIR__ . '/config.inc.php')): ?>
<?php

# 站点根目录
define('W3_ROOT_DIR', __DIR__ . DIRECTORY_SEPARATOR);

# 插件目录
define('W3_PLUGIN_DIR', W3_ROOT_DIR . 'app/plugins/');

# 主题目录
define('W3_TEMPLATE_DIR', W3_ROOT_DIR . 'app/themes/');

# 载入框架functions
require W3_ROOT_DIR . 'system/W3/functions.php';

# 载入框架Loader
require W3_ROOT_DIR . 'system/W3/Loader.php';

# 设置框架要搜索的目录路径
\W3\Loader::directory(W3_ROOT_DIR . 'system');

# 开启框架自动加载
\W3\Loader::autoLoad();

# 设置变量数据
\W3\Config::instance()->default([

	# 程序版本
	'version' => '1.2.0',

	# 调试
	'debug' => 1,

	# 开始时间
	'startTime' => microtime(1),

	# 启动内存
	'startMemory'=> function_exists('memory_get_usage') ? memory_get_usage() : 0
]);

else:

    header('Content-Type: UTF-8; charset=text/html', true);
	
    require_once __DIR__ . '/config.inc.php';

    //判断是否已经安装
    try {
        $installed = \W3\Db::instance()
		    ->select()
		    ->from('table.options')
			->where('name = ?', 'installed')
			->fetch();
        if (empty($installed) || $installed['value'] == 1) {
			
            \W3\Response::instance()
                ->clear()
				->header('Content-Type', 'UTF-8; charset=text/html')
                ->code(404)
                ->write('Setup has checked that the program has been installed successfully!')
                ->send();
            exit();
        }
    } catch (Exception $e) {
        // do nothing
    }

endif;

ob_start();

// 挡掉可能的跨站请求
if (!empty($_GET) || !empty($_POST)) {
    if (empty($_SERVER['HTTP_REFERER'])) {
        exit;
    }

    $parts = parse_url($_SERVER['HTTP_REFERER']);
	if (!empty($parts['port'])) {
        $parts['host'] = "{$parts['host']}:{$parts['port']}";
    }

    if (empty($parts['host']) || $_SERVER['HTTP_HOST'] != $parts['host']) {
        exit;
    }
}

/**
 * 获取传递参数
 *
 * @_r string $name 参数名称
 * @_r string $default 默认值
 * @return string
 */
function _r($name, $default = NULL) {
    return isset($_REQUEST[$name]) ?
        (is_array($_REQUEST[$name]) ? $default : $_REQUEST[$name]) : $default;
}

/**
 * 获取多个传递参数
 *
 * @return array
 */
function _rFrom() {
    $result = [];
    $_rs = func_get_args();

    foreach ($_rs as $_r) {
        $result[$_r] = isset($_REQUEST[$_r]) ?
            (is_array($_REQUEST[$_r]) ? NULL : $_REQUEST[$_r]) : NULL;
    }

    return $result;
}

/**
 * 输出传递参数
 *
 * @_r string $name 参数名称
 * @_r string $default 默认值
 * @return string
 */
function _v($name, $default = '') {
    echo _r($name, $default);
}

/**
 * 获取url地址
 *
 * @return string
 */
function _u() {

    return rtrim(\W3\Request::instance()->rootUrl(true), '/');

    //$url = \W3\Request::instance()->url(true);
    //return dirname($url);
}

function message($msg = NULL)
{
	echo $msg;
    exit;
}

/**
 * 获取数据大小单位
 * @param int $byte 字节
 * @return string
 */
function get_byte($byte) {
	if($byte < 1024) {
		return $byte.' Byte';
	}elseif($byte < 1048576) {
		return round($byte/1024, 2).' KB';
	}elseif($byte < 1073741824) {
		return round($byte/1048576, 2).' MB';
	}elseif($byte < 1099511627776) {
		return round($byte/1073741824, 2).' GB';
	}else{
		return round($byte/1099511627776, 2).' TB';
	}
}

/**
 * 获取语言列表
 * 
 * @access private
 * @return array
 */
function getLangs()
{
    $dir = W3_ROOT_DIR . 'system/lang';
    $files = glob($dir . '/*.php');
    $langs = [];
    if (!empty($files)) {
        foreach ($files as $file) 
	    {
            list($name) = explode('.', basename($file));
            $langs[$name] = __($name);
        }
        ksort($langs);
    }
    return $langs;
}

function _view($name) 
{
	return W3_ROOT_DIR . "system/Module/install/view/{$name}.php";
}

/** 获取语言 */
$lang = _r('lang', \W3\Cookie::get('__lang'));
$langs = getLangs();

if (empty($lang) || (!empty($langs) && !isset($langs[$lang]))) {
    $lang = 'zh_CN';
}

\W3\Cookie::set('__lang', $lang);

$action = _r('action');
$method = strtoupper($_SERVER['REQUEST_METHOD']);

// 第一步，阅读
if(empty($action)) {
	include _view('header');
	include _view('license');
	include _view('footer');
} elseif($action == 'env') {
	include _view('header');
	include _view('env');
	include _view('footer');
} elseif($action == 'start' || $action == 'finish') {

/**
 * 判断是否兼容某个环境(perform)
 *
 * @_r string $adapter 适配器
 * @return boolean
 */
function _p($adapter) {
	
	$adapters = \W3\Db::drivers();
	
	if(isset($adapters[$adapter])){
		$class = $adapters[$adapter];
        if ($class::isAvailable()) {
            return true;
        }
	}
	return false;
}

    $adapters = \W3\Db::drivers();
	
	// 判断是否兼容某个环境
    foreach ($adapters as $firstAdapter => $class) 
	{
        if (_p($firstAdapter)) {
            break;
        }
    }
    $adapter = _r('dbAdapter', $firstAdapter);

	if($action == 'start'){
		
	    include _view('header');
	    include _view('start');
	    include _view('footer');
		
		exit;
	} elseif($action == 'finish') {
		
	    if($method == 'GET') { 
		
		    message(__('您没有执行安装步骤, 请您重新安装!'));
		
	    } elseif($method == 'POST') {

		$dbAdapter = $adapter;		
		$dbHost = _r('dbHost');	
		$dbUser = _r('dbUser');	
		$dbPassword = _r('dbPassword');
		$dbCharset = _r('dbCharset');
		$dbPort = _r('dbPort');
		$dbName = _r('dbName');	
		$dbPrefix = _r('dbPrefix');
		$dbEngine = _r('dbEngine');

		$userUrl = _r('userUrl');	
		$userName = _r('userName');	
		$userPassword = _r('userPassword');
		$userMail = _r('userMail');
		
		empty($dbAdapter) AND message(__('dbAdapter_is_empty'));
		empty($dbHost) AND message(__('dbHost_is_empty'));
		empty($dbUser) AND message(__('dbUser_is_empty'));
		empty($dbPassword) AND message(__('dbPassword_is_empty'));
		empty($dbCharset) AND message(__('dbCharset_is_empty'));
		empty($dbPort) AND message(__('dbPort_is_empty'));
		empty($dbName) AND message(__('dbName_is_empty'));
		empty($dbPrefix) AND message(__('dbPrefix_is_empty'));
		empty($userUrl) AND message(__('请填写您的网站地址'));
		empty($userName) AND message(__('请填写您的用户名'));
		empty($userPassword) AND message(__('用户密码为空'));
		empty($userMail) AND message(__('请填写您的邮箱地址'));
		
        $installDb = new \W3\Db($dbAdapter, $dbPrefix);
        $installDb->addServer([
            'host' => $dbHost,
            'user' => $dbUser,
            'password' => $dbPassword,
            'charset' => $dbCharset,
            'port' => $dbPort,
            'dbname' => $dbName,
            'engine' => 'MyISAM',
        ]);
        \W3\Db::setInstance($installDb);

        /** 检测数据库配置 */
        try {
            $installDb->query('SELECT 1=1')->affected();
            } catch (\Exception $e) {
			
			$s = '安装程序捕捉到以下错误: 程序被终止, 请检查您的配置信息.<br><br>' . $e->getMessage();
			if(strstr($s,'[1049]')){
				$s = '数据库名错误';
			} else if(strstr($s,'[1045]')){
				$s = '数据库密码错误';
			} else if(strstr($s,'[1044]')){
				$s = '数据库帐户错误';
			}
			message($s);
        } catch (\Exception $e) {
            message(__('安装程序捕捉到以下错误: " %s ". 程序被终止, 请检查您的配置信息.', $e->getMessage()));
        }

        $type = explode('_', $dbAdapter);
        $type = array_pop($type);
        $type = $type == 'Mysqli' ? 'Mysql' : $type;		
		
        $s = file_get_contents(W3_ROOT_DIR . "system/Module/install/sql/{$type}.sql");
        $s = str_replace('{engine}', $dbEngine, $s);
        $s = str_replace('{pre}', $dbPrefix, $s);
        //$s = str_replace(";\r\n", ";\n", $s);
        $s = preg_replace('/#(.*?)\r\n/i', "", $s);
        $arr = explode(";\r\n", $s);

        foreach ($arr as $sql) {
            $sql = trim($sql);
            if (empty($sql)) {
                continue;
            }
            $arr = explode(";\n", $s);
			
			empty($sql) and message("sql: {$sql}");
			
            $installDb->query($sql)->affected() === FALSE and message("sql: {$sql}");
        }

        $options = [
            'theme' => 'default',
            'theme:default' => '[]',
            'timezone' => '28800',
            'lang' => $lang,
            'charset' => 'UTF-8',
            'contentType' => 'text/html',
            'gzip' => 0,
            'plugins' => '[]',
            'title' => 'Hello World',
            'description' => 'Your description here.',
            'keywords' => 'W3,php,blog',
            'rewrite' => 0,
            'commentsRequireModeration' => 0,
			'commentsWhitelist' => 0,
            'commentDateFormat' => 'F jS, Y \a\t h:i a',
			
			// 可以配置单独的 CDN 域名：比如：http://upload.domain.com/upload
			'cdnUrl' => $userUrl . '/app/uploads',
            'siteUrl' => $userUrl,
			'frontPage' => '',
            'allowRegister' => 0,
            'defaultAllowComment' => 1,
            'pageSize' => 5,
            'postListSize' => 10,
            'commentsListSize' => 10,
            'commentsHTMLTagAllowed' => '',
            'postDateFormat' => 'Y-m-d',
            'commentsMaxNestingLevels' => 5,
            'commentsPostTimeout' => 24 * 3600 * 30,
            'commentsUrlNofollow' => 1,
            'commentsShowUrl' => 1,
            'commentsMarkdown' => 0,
            'commentsPageBreak' => 0,
            'commentsThreaded' => 1,
            'commentsPageSize' => 20,
            'commentsPageDisplay' => 'last',
            'commentsOrder' => 'ASC',
            'commentsCheckReferer' => 1,
            'commentsAutoClose' => 0,
            'commentsPostIntervalEnable' => 1,
            'commentsPostInterval' => 60,
            'commentsShowCommentOnly' => 0,
            'routes' => '',
            'attachmentTypes' => '@image@',
            'secret' => \W3\Util::randstring(64),
            'installed' => 0
        ];
		
		/** 初始化全局变量 */
        foreach ($options as $key => $value)
		{
            if ($key == 'installed') {
                $value = 1;
            }
			
		    $installDb->insert('table.options')->rows(['name' => $key, 'uid' => 0, 'value' => $value])->affected();
		}
		
		$time = \W3\Timer::instance()->time();
		
        /** 初始化分类 */
		$installDb->insert('table.metas')->rows(array(
		    'name' => __('默认分类'), 
			'alias' => 'default', 
			'type' => 'category',			
			'description' => __('只是一个默认分类'),
			'count' => 1, 
			'order' => 0
		))->affected();
		
        /** 初始化内容 */
		$installDb->insert('table.contents')->rows(array(
		    'title' => __('欢迎使用 W3'), 
			'alias' => 'start',
            'type' => 'post',			
			'created' => $time, 
			'modified' => $time,
			'uid' => 1, 
			'mids' => '1', 
			'commentsNum' => 1, 
			'allowComment' => 1,
			'text' => __('本页面由 W3 创建, 这只是个测试页面.')
		))->affected();

        /** 初始化关系 */
        $installDb->insert('table.relate')->rows(array(
		    'mid' => 1, 
			'cid' => 1
		))->affected();
		
        $installDb->insert('table.contents')->rows(array(
		    'title' => __('关于'), 
			'alias' => 'start-page',
            'type' => 'page',			
			'created' => $time, 
			'modified' => $time,
			'uid' => 1, 
			'mids' => '0', 
			'commentsNum' => 0, 
			'allowComment' => 1,
			'text' => __('本页面由 W3 创建, 这只是个测试页面.')
		))->affected();
		
        /** 初始化评论 */
        $installDb->insert('table.comments')->rows(array(
		    'uid' => 1,
		    'cid' => 1, 
			'created' => $time, 
			'ownerId' => 1,
			'ip' => \W3\Request::instance()->ip(true), 
			'text' => '欢迎加入 W3 大家族',
         	'parent' => 0		
		))->affected();

        /** 初始化用户 */
        $password = empty($userPassword) ? substr(uniqid(), 7) : $userPassword;
        $installDb->insert('table.users')->rows(array(
		    'name' => $userName, 
			'password' => \W3\Util::passwordHash($password), 
			'salt' => sha1(\W3\Util::randstring(20)),
			'mail' => $userMail,
			'nickName' => $userName, 
			'group' => 'admin',
			'ip' => 0, 		
			'created' => $time, 
			'logged' => $time, 
			'activated' => $time
		))->affected();

    $code = "<" . "?php

# 站点根目录
define('W3_ROOT_DIR', __DIR__ . DIRECTORY_SEPARATOR);

# 插件目录
define('W3_PLUGIN_DIR', W3_ROOT_DIR . 'app/plugins/');

# 主题目录
define('W3_TEMPLATE_DIR', W3_ROOT_DIR . 'app/themes/');

# 载入框架functions
require W3_ROOT_DIR . 'system/W3/functions.php';

# 载入框架Loader
require W3_ROOT_DIR . 'system/W3/Loader.php';

# 设置框架要搜索的目录路径
\W3\Loader::directory(W3_ROOT_DIR . 'system');

# 开启框架自动加载
\W3\Loader::autoLoad();

# 设置变量数据
\W3\Config::instance()->default([

	# 程序版本
	'version' => '1.2.0',

	# 默认关闭调试模式
	'debug' => 0,

	# 开始时间
	'startTime' => microtime(1),

	# 启动内存
	'startMemory'=> function_exists('memory_get_usage') ? memory_get_usage() : 0
]);

\$db = new \W3\Db('$dbAdapter', '$dbPrefix');
\$db->addServer([
    'host' => '$dbHost',
    'user' => '$dbUser',
    'password' => '$dbPassword',
    'charset' => '$dbCharset',
    'port' => '$dbPort',
    'dbname' => '$dbName',
    'engine' => 'MyISAM',
]);
\W3\Db::setInstance(\$db);
";

        if (!\W3\Util::isAppEngine()) {
            @file_put_contents('./config.inc.php', $code);
        }

        if (!file_exists('./config.inc.php')) {
            message(__('安装程序无法自动创建 <strong>config.inc.php</strong> 文件<br />您可以在网站根目录下手动创建 <strong>config.inc.php</strong> 文件, 并复制如下代码至其中<p><textarea rows="5" onmouseover="this.select();" class="w-100 mono" readonly>%s</textarea></p>', htmlspecialchars($code)));
		}
		
        !is_dir(W3_ROOT_DIR.'app/uploads') && mkdir(W3_ROOT_DIR . 'app/uploads', 0777);


	    include _view('header');
	    include _view('finish');
	    include _view('footer');

        exit;
		}
    }
}
?>